package com.qifenqian.turbot.base

import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.qifenqian.turbot.R
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.NetUtils
import kotlinx.android.synthetic.main.layout_error.view.*
import org.jetbrains.anko.support.v4.toast

/**
 * @author H
 * @createDate 2018/8/9 19:02
 * @reference
 * @updateDate
 * @description
 * @detail
 * @since
 */
abstract class BaseFragment<P : BasePresenter<V, *>, V> : Fragment() {


    protected var mPresenter: P? = null
    protected lateinit var mView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Lcat.d("当前Fragment", javaClass.simpleName)
        mView = inflater.inflate(bindLayoutId(), container, false)
        mPresenter = bindPresenter()
        initial(mView)
        return mView
    }

    @LayoutRes
    abstract fun bindLayoutId(): Int

    abstract fun bindPresenter(): P?
    /**
     * 判断当前是否有网络,点击事件等调用
     */
    fun isNetworkConnected(): Boolean {
        if (!NetUtils.isNetworkAvailable(activity)) {
            toast("没有网络")
            return false
        }
        return true
    }

    abstract fun initial(view: View)

    override fun onResume() {
        super.onResume()
        if (mPresenter != null) {
            mPresenter!!.attachView(this as V)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mPresenter != null) {
            mPresenter!!.detachView()
        }
    }

    fun showErrorPage(onClickListener: View.OnClickListener?, msg: String? = "错误", attachToRoot: Boolean = false) {
        val lyContent = mView.findViewById<ViewGroup>(R.id.ly_content)
        lyContent.removeAllViews()
        val view = LayoutInflater.from(activity).inflate(R.layout.layout_error, lyContent, attachToRoot)
        view.tv_error_message.text = msg
        view.btn_error_retry.setOnClickListener {
            onClickListener?.onClick(view.btn_error_retry)
        }
    }
}